//
//  PostPublishViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/12/10.
//  Copyright © 2020 王洋. All rights reserved.
//
#import "AFNetworking.h"
#import "PostImgUploadCell.h"

#import "RelatedTopicViewController.h"

#import "PostPublishViewController.h"

@interface PostPublishViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, TZImagePickerControllerDelegate, UITextViewDelegate, UITextFieldDelegate>


@property (weak, nonatomic) IBOutlet UIButton *postBtn;


@property (weak, nonatomic) IBOutlet UITextField *titleTF;

@property (weak, nonatomic) IBOutlet UITextView *contentTV;


@property (weak, nonatomic) IBOutlet UICollectionView *collectionview;

@property (weak, nonatomic) IBOutlet UIView *relateThemeControl;


@property (nonatomic, strong) NSMutableArray <CommonMediaModel *>*imageArray;

@end

@implementation PostPublishViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initView];
    [self prepareData];
}

- (void)prepareData {
    CommonMediaModel *model = [[CommonMediaModel alloc] init];
    model.url = @"";
    self.imageArray = @[].mutableCopy;
    [self.imageArray addObject:model];
    [self.collectionview reloadData];
}

- (void)initView {
    
    self.title = @"帖子";
    self.view.backgroundColor = UIColorHex(0xffffff);

    UIButton *publishBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    publishBtn.frame = CGRectMake(0,0,52,24);
    publishBtn.layer.cornerRadius = 12.0f;
    [publishBtn setBackgroundColor:UIColorHex(0xFF4242)];
    publishBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [publishBtn setTitle:@"发布" forState:UIControlStateNormal];
    [publishBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [publishBtn addTarget:self action:@selector(publishAction) forControlEvents:UIControlEventTouchUpInside];
    
    [publishBtn.widthAnchor constraintEqualToConstant:52].active =YES;
    [publishBtn.heightAnchor constraintEqualToConstant:24].active =YES; 
    
    UIBarButtonItem *publishItem = [[UIBarButtonItem alloc] initWithCustomView:publishBtn];

    self.navigationItem.rightBarButtonItems =@[publishItem];
    
    UICollectionViewFlowLayout * flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    self.collectionview.collectionViewLayout = flowLayout;
    self.collectionview.delegate = self;
    self.collectionview.dataSource = self;
    self.collectionview.showsHorizontalScrollIndicator = NO;
    self.collectionview.showsVerticalScrollIndicator = NO;

    [self.collectionview registerNib:[UINib nibWithNibName:@"PostImgUploadCell" bundle:nil] forCellWithReuseIdentifier:@"PostImgUploadCellID"];
    
    self.collectionview.backgroundColor = [UIColor clearColor];
    
    self.contentTV.delegate = self;
    self.titleTF.delegate = self;
    
    if (self.model) {
        [self.postBtn setTitle:self.model.themeTitle forState:UIControlStateNormal];
        self.postBtn.titleLabel.font = [UIFont systemFontOfSize:12];
        [self.postBtn setTitleColor:UIColorHex(0xFF4242) forState:UIControlStateNormal];
        [self.postBtn setBackgroundColor:UIColorHex(0xFFF0F0)];
    }

    [self initViewAction];
}

//仿placeholder
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
    if ([textView.text isEqualToString:@"请详细描述帖子内容，详细内容更容易解读（10字以上）"]) {
        textView.textColor = UIColorHex(0x333333);
        textView.text = @"";
    }
    return YES;
}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView {
    if ([textView.text isEqualToString:@""]) {
        textView.textColor = UIColorHex(0xbbbbbb);
        textView.text = @"请详细描述帖子内容，详细内容更容易解读（10字以上）";
    }
    return YES;
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.postBtn pp_clipCorners:UIRectCornerAllCorners radius:self.postBtn.frame.size.height/2];
    });
}

- (void)initViewAction {
    
    self.relateThemeControl.userInteractionEnabled = YES;
    WEAKSELF
    [self.relateThemeControl addGestureTapEventHandle:^(id  _Nonnull sender, UITapGestureRecognizer * _Nonnull gestureRecognizer) {
        RelatedTopicViewController *vc = [[RelatedTopicViewController alloc] init];
        
        vc.RelatedTopicBlock = ^(CommunityThemeModel * _Nonnull model) {
            
            self.model = model;
            [self.postBtn setTitle:self.model.themeTitle forState:UIControlStateNormal];
            self.postBtn.titleLabel.font = [UIFont systemFontOfSize:12];
            [self.postBtn setTitleColor:UIColorHex(0xFF4242) forState:UIControlStateNormal];
            [self.postBtn setBackgroundColor:UIColorHex(0xFFF0F0)];
        };
        

        
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
    
}

- (void)publishAction {
    
    if (self.titleTF.text.length >= 5 && self.titleTF.text.length <= 20) {
        
        if (![self.contentTV.text isEqualToString:@"请详细描述帖子内容，详细内容更容易解读（10字以上）"] && self.contentTV.text.length >= 10) {
            [self request_publishPost];
        } else {
            [SVProgressHUD showErrorWithStatus:@"帖子内容10字以上"];
            [SVProgressHUD dismissWithDelay:1];
        }        
    } else {
        [SVProgressHUD showErrorWithStatus:@"帖子标题为5~20字"];
        [SVProgressHUD dismissWithDelay:1];
    }
    
}

- (void)uplodPhoto {

    NSInteger count = 9;
    count = 10 - self.imageArray.count;
    
    TZImagePickerController *vc = [[TZImagePickerController alloc]
                                   initWithMaxImagesCount:count delegate:self];

    vc.naviBgColor = default_color_white;
    vc.naviTitleColor = default_color_black;
    vc.barItemTextColor = default_color_black;

    vc.photoWidth = 2048.0f;
    
    vc.preferredLanguage = @"zh-Hans";

    //筛选到只剩图片
    vc.allowPickingVideo = NO;
    vc.allowPickingMultipleVideo = NO;
    vc.allowPickingGif = NO;
    vc.allowPickingVideo = NO;

    vc.showSelectedIndex = YES;
    vc.showSelectBtn = YES;

    //裁剪
    vc.allowCrop = YES;
    vc.cropRect = CGRectMake( 0 ,(TTScreenHeight - TTScreenWidth)/2, TTScreenWidth, TTScreenWidth);

    WEAKSELF
    [vc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        
        // 准备保存结果的数组，元素个数与上传的图片个数相同，先用 NSNull 占位
        NSMutableArray* result = [NSMutableArray array];
        for (int i = 0; i < photos.count; i++) {
            [result addObject:[NSNull null]];
        }
        
        dispatch_group_t group = dispatch_group_create();

        [SVProgressHUD showWithStatus:@"正在上传图片"];
        for (NSInteger i = 0; i < photos.count; i++)
        {
            dispatch_group_enter(group);
            dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                
                // ContentType设置
                AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
                manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"image/jpeg",@"image/png",@"application/octet-stream",@"text/json",nil];
                manager.requestSerializer= [AFHTTPRequestSerializer serializer];
                manager.responseSerializer= [AFHTTPResponseSerializer serializer];
                [manager.requestSerializer setValue:[TTUserModel sharedObject].token forHTTPHeaderField:@"token"];
                
                // 上传完整地址
                NSString * urlString = [NSString stringWithFormat:@"%@headImgUpload",TT_Global_Service_Domain];
                
                [manager POST:urlString parameters:nil headers:@{} constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
                            
                    if (photos[i] != nil) {
                    NSData *data = UIImageJPEGRepresentation(photos[i], 0.2f);
                    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                    formatter.dateFormat = @"yyyyMMddHHmmss";
                    NSString *str = [formatter stringFromDate:[NSDate date]];
                    NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
                    [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/jpg"];
                    }
                    
                } progress:^(NSProgress * _Nonnull uploadProgress) {
                    NSLog(@"%.2f",uploadProgress.fractionCompleted);

                } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

                    NSString *resultStr = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];

                    if ([resultStr isKindOfClass:[NSString class]]) {
                        
                        @synchronized (result) {
                            result[i] = resultStr;
                        }
                    }
                    dispatch_group_leave(group);
                    
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    dispatch_group_leave(group);

                }];
            });
           
        }
        
        dispatch_group_notify(group, dispatch_get_main_queue(), ^{
            NSLog(@"上传完成!");
            [SVProgressHUD showSuccessWithStatus:@"上传成功"];
            [SVProgressHUD dismissWithDelay:0.5];

            [weakSelf removeEmptyPhotoModelFromArray:weakSelf.imageArray];

            for (int i = 0; i < result.count; i++) {
                NSString *imgStr = result[i];
                if ([imgStr isKindOfClass:[NSString class]]) {
                    CommonMediaModel *model = [[CommonMediaModel alloc] init];
                    model.url = imgStr;
                    [weakSelf.imageArray addObject:model];
                }
            }
            if (weakSelf.imageArray.count < 9) {
                [weakSelf addEmptyPhotoModelToArray:weakSelf.imageArray];
            }
            
            [weakSelf.collectionview reloadData];

        });
    }];

    vc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:vc animated:YES completion:nil];
}

#pragma mark 图片数组加空
- (void)addEmptyPhotoModelToArray:(NSMutableArray<CommonMediaModel *>*)array {
    CommonMediaModel * model = [[CommonMediaModel alloc] init];
    [array addObject:model];
}

#pragma mark 图片数组去掉空数据
- (void)removeEmptyPhotoModelFromArray:(NSMutableArray<CommonMediaModel *>*)array {
    for (CommonMediaModel *model in array) {
        if (model.url.length == 0) {
            [array removeObject:model];
        }
    }
}

#pragma mark collectionview

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    PostImgUploadCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PostImgUploadCellID" forIndexPath:indexPath];
    
    [cell fillCellWithModel:self.imageArray[indexPath.row]];
    WEAKSELF
    cell.PostImgUploadCellBlock = ^(PostImgUploadCellActionType type) {
        
        switch (type) {
            case PostImgUploadCellActionType_del:{
                
                //删除图片的操作
                [weakSelf.imageArray removeObjectAtIndex:indexPath.row];
                
                [weakSelf removeEmptyPhotoModelFromArray:weakSelf.imageArray];
                if (weakSelf.imageArray.count < 9) {
                    [weakSelf addEmptyPhotoModelToArray:weakSelf.imageArray];
                }
                
                [weakSelf.collectionview reloadData];
                
            } break;
            case PostImgUploadCellActionType_tap:{
                
                [weakSelf uplodPhoto];

                
            } break;
            default:
                break;
        }
    };
    
    return cell;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.imageArray.count;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    return CGSizeMake(110, 110);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {


}



- (void)request_publishPost {
        
    NSMutableDictionary *dic = @{}.mutableCopy;

    [dic setValue:self.contentTV.text forKey:@"content"];
    [dic setValue:self.titleTF.text forKey:@"title"];
    
    //类型（1：谈婚-帖子，2：论嫁-话题） 必传
    [dic setValue:@"1" forKey:@"type"];
    [dic setValue:@"2" forKey:@"source"];
    
    NSMutableArray *sysMediaList = @[].mutableCopy;
    for (CommonMediaModel *model in self.imageArray) {
        
        if (model.url.length > 0) {
            [sysMediaList addObject:model.url];
        }
    }
    [dic setValue:sysMediaList forKey:@"sysMediaList"];


    [dic setValue:[TTUserModel sharedObject].userId forKey:@"userId"];
    [dic setValue:self.model.themeId forKey:@"themeId"];
    
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_PublishPost];
    
    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在发布"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {

                [weakSelf.navigationController popViewControllerAnimated:YES];
            } else {
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
    }];
}

@end
